// 文件名应为：CustomUserDetailsService.java
package com.example.service.impl;

import com.example.annotation.LogOperation;
import com.example.domain.po.User;
import com.example.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
/**
 * 自定义用户详细服务类，实现Spring Security的UserDetailsService接口
 * 用于加载用户信息，包括用户名、密码和权限等
 */
@Service
@RequiredArgsConstructor

public class CustomUserDetailsService implements UserDetailsService {

    // 用户映射器，用于与数据库交互用户信息
    private final UserMapper userMapper;
    // 密码编码器，用于编码和匹配密码
    private final PasswordEncoder passwordEncoder;

    /**
     * 根据用户名加载用户信息
     * 此方法用于Spring Security框架内部验证用户身份
     *
     * @param username 用户名，用于查询用户信息
     * @return UserDetails对象，包含用户的信息和权限
     * @throws UsernameNotFoundException 如果用户不存在，则抛出此异常
     */
    @LogOperation("springsecurtiy内部校验密码")
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过用户名查询用户信息
        User user = userMapper.findByUsername(username);
        // 如果用户不存在，抛出异常
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        // 查询用户的角色名称，并将其转换为GrantedAuthority对象列表
        List<String> roleNames = userMapper.findRoleNamesByUsername(username);
        List<GrantedAuthority> authorities = roleNames.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                .collect(Collectors.toList());

        // 返回构建的UserDetails对象，包含用户名、密码和权限
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authorities
        );
    }
}

